<?php
namespace App\Logic\Shipping;

use App\Models\Shipping\SSkuTotal;
use App\Models\Shipping\SSkuTotalApply;
use Illuminate\Support\Facades\DB;
class InitSSkuTotalDiffer
{
    /**
     * 设定：每月15日与月末
     */
    public static function init(){
        $t = date('t');
        $day = date('j');//当前月中的第几天
        if($day == 15 || $day == $t){
            $date = self::_getDateInterval($day);
            SSkuTotal::query()->orderBy('id')
                ->chunk(500, function ($items) use (&$date){
                    DB::beginTransaction();
                    try{
                        foreach($items as $item){
                            $mPSkuId = $item->sku->m_psku_id ?? 0;
                            if(!$mPSkuId)continue;
                            $storageNum = SSkuTotal::getStorageNum($date[0],$date[1],$mPSkuId);
                            $applyNum = self::_getApplyNum($date[0],$item->psku_id);
                            $item->t_differ += $storageNum - $applyNum;
                            $item->save();
                        }
                        DB::commit();
                    }catch(\Exception $e){
                        DB::rollBack();
                        report($e);
                    }
            });
        }else{
            die('不在更新日期内');
        }
    }

    private static function _getApplyNum($date,$pSkuId){
        $num = SSkuTotalApply::query()
            ->where('shipping_date',$date)
            ->where('psku_id',$pSkuId)
            ->value('apply_num');
        return $num ?: 0;
    }

    private static function _getDateInterval($day){
        $re = [];
        if($day == 15){
            $re[0] = date('Y-m-01');
            $re[1] = date('Y-m-15');
        }else{
            $re[0] = date('Y-m-16');
            $re[1] = date('Y-m-t');
        }
        return $re;
    }
}
